﻿#region Usings
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using BK.Financisto;
using BK.Model;

using BestExpenses;

using Import.Lib;

using Lib.Data.CSV;
using Lib.General;
#endregion

namespace BK.Conversion.Financisto
{
    internal class Program
    {
        #region Class Methods
        private static void Export<TEntity>(string fileName) where TEntity : ICsvEntity, ICommonExpense, new()
        {
            CsvReader csvReader = new CsvReader(fileName, Encoding.Unicode, ';');

            CsvReadingResult<TEntity> csvReadingResult = csvReader.ReadAsEntities<TEntity>();

            if (csvReadingResult.IsValid)
            {
                IEnumerable<CommonExpense> commonExpenses = csvReadingResult.Items.Select(x => new CommonExpense(x));

                BkDataContext commonDataContext = new BkDataContext();
                
                foreach (CommonExpense commonExpense in commonExpenses)
                {
                    commonDataContext.CommonExpenses.Add(commonExpense);
                }

                commonDataContext.SaveChanges();

                Logger.Info("Data was imported to database");
            }
            else
            {
                Logger.Error(csvReadingResult.ToString());
            }
        }

        private static void Main(string[] args)
        {
            Logger.Info(string.Format("Try read csv from {0}", args[0]));

            string fileName = args[0];
            EntityKind entityKind = (EntityKind) Enum.Parse(typeof(EntityKind), args[1]);

            switch (entityKind)
            {
                case EntityKind.BestExpense: 
                    Export<BestExpenseEntity>(fileName);
                    break;
                case EntityKind.Financisto:
                    Export<FinancistoExpense>(fileName);
                    break;
                default:
                    throw new NotSupportedException();
            }
        }
        #endregion
    }
}